import {deepCopy, messages} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Button, Form, Switch, Input, Row, Col, message, Select ,Checkbox, Popover, Icon } from 'antd'
const { Option } = Select;
const FormItem = Form.Item;
import defaultExpenseTypeIcon from 'images/expense/default-expense-type.png'
import 'styles/setting/expense-type/new-expense-type/expense-type-base.scss'
import baseService from 'share/base.service'
import IconSelector from 'containers/setting/expense-type/new-expense-type/icon-selector'
import expenseTypeService from 'containers/setting/expense-type/expense-type.service'
import menuRoute from 'routes/menuRoute'
import { LanguageInput } from 'components/index';
import Chooser from "components/chooser";
import Condition from 'components/condition'
const { If } = Condition;

class ExpenseTypeBase extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      showIconSelectorFlag: false,
      expenseTypeCategory: [],
      name: '',
      nameI18n: [],
      instructions: '',
      instructionsI18n: [],
      icon: {
        iconURL: '',
        iconName: ''
      },
      valid: 0,
      subsidyType: 0,
      saving: false,
      expenseTypePage: menuRoute.getRouteItem('expense-type'),
      expenseTypeDetailPage: menuRoute.getRouteItem('expense-type-detail')
    }
  }

  componentDidMount(){
    if(!this.props.expenseType){
      if(!this.props.expenseTypeSetOfBooks.id){
        this.goBack();
      } else {
        Promise.all([
          baseService.getExpenseTypeCategory(this.props.expenseTypeSetOfBooks.id),
          expenseTypeService.getExpenseTypeCode(this.props.expenseTypeSetOfBooks.id)
        ]).then(res => {
          this.setState({ expenseTypeCategory: res[0].data });
          this.props.form.setFieldsValue({ code: res[1].data.rows });
        });
      }
    } else {
      baseService.getExpenseTypeCategory(this.props.expenseType.setOfBooksId).then(res => {
        this.setState({ expenseTypeCategory: res.data });
        this.setFieldsByExpenseType(this.props);
      });
    }
  }

  goBack = () => {
    this.context.router.push(this.state.expenseTypePage.url)
  };

  setFieldsByExpenseType = (props) => {
    const { expenseType } = props;
    let valueWillSet = this.props.form.getFieldsValue();
    let excludeFormItemKeys=['type','parentId'];
    Object.keys(valueWillSet).map(key => {
      if (~excludeFormItemKeys.indexOf(key)) {
        return;
      }
      valueWillSet[key] = expenseType[key];
    });
    this.setState({
      icon: {
        iconURL: expenseType.iconURL,
        iconName: expenseType.iconName
      },
      nameI18n: expenseType.i18n.name,
      name: expenseType.name,
      instructions: expenseType.instructions,
      instructionsI18n: expenseType.i18n.instructions,
      valid: Number(expenseType.valid),
      subsidyType: expenseType.subsidyType
    }, () => {
      valueWillSet.pasteInvoiceNeeded = Number(valueWillSet.pasteInvoiceNeeded);
      valueWillSet.valid = Number(valueWillSet.valid);
      valueWillSet.serviceFeeSplit = Number(valueWillSet.serviceFeeSplit || 0);
      this.props.form.setFieldsValue(valueWillSet)
    })
  };

  handleSave = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if(!err){
        const { icon, nameI18n, expenseTypeDetailPage, instructionsI18n } = this.state;
        const { copy } = this.props;
        if(icon.iconURL === ''){
          message.error(messages('setting.key517'/*请选择费用图标*/));
          return;
        }
        values.pasteInvoiceNeeded = Boolean(values.pasteInvoiceNeeded);
        values.valid = Boolean(values.valid);
        values.iconURL = icon.iconURL;
        values.iconName = icon.iconName;
        values.crossCheckStatus = 0;
        values.setOfBooksId = this.props.expenseTypeSetOfBooks.id;
        values.erApportionEnabled = false;
        values.apportionEnabled = false;
        if(!values.apportionmentDataScope) {
          values.apportionmentDataScope = 0;
        }
        if(!values.pushType){
          values.pushType = 'ALL'
        }
        if(!values.isAmountEditable && values.isAmountEditable !== false){
          values.isAmountEditable = true;
        }
        values.i18n = {
          name: nameI18n,
          instructions: instructionsI18n
        };
        values.apportionEnabledConfig.map(item => {
          values[item] = true
        });
        delete values.apportionEnabledConfig;
        this.setState({ saving: true });
        if(this.props.expenseType){
          let temp = deepCopy(this.props.expenseType);
          if(temp.supplierType !== 0 && temp.supplierType !== 15){
            values.pasteInvoiceNeeded = temp.pasteInvoiceNeeded;
          }
          let target = Object.assign({}, temp, values);
          if (target.parentId && target.parentId.length > 0) {
            target.parentId = target.parentId[0].id;
          }
          target.depth = Number(target.depth);
          if (target.depth === 1) {
            target.parentId = null;
          }
          expenseTypeService.saveExpenseType(target, copy)
            .then(res => {
              this.setState({ saving: false });
              message.success(messages('common.operate.success'));
              copy
                ? (() => {
                  this.context.router.push(this.state.expenseTypeDetailPage.url.replace(':expenseTypeId', res.data.rows.id));
                  this.props.onSave('base', res.data.rows.id);
                })()
                : this.props.onSave();
            })
            .catch(e => {
              this.setState({ saving: false });
              if (e && e.response && e.response.data) {
                let data = e.response.data;
                if (data.validationErrors.length > 0) {
                  data.validationErrors.map(error => {
                    if (error.externalPropertyName === 'code unique') {
                      message.error(messages('setting.key518'/*编码已存在，请重新输入*/));
                    }
                  });
                }
              }
            })
        } else {
          values.sequence = 0;
          let target = deepCopy(values)
          if (target.parentId && target.parentId.length > 0) {
            target.parentId = target.parentId[0].id;
          }
          target.depth = Number(target.depth);
          if (target.depth === 1) {
            target.parentId = null;
          }
          target.titleRequired = false;
          expenseTypeService.saveExpenseType(target).then(res => {
            this.setState({ saving: false });
            message.success(messages('common.operate.success'));
            this.context.router.replace(expenseTypeDetailPage.url.replace(':expenseTypeId', res.data.rows.id));
            this.props.onSave('custom',  res.data.rows.id);
          }).catch(e => {
            this.setState({ saving: false });
            if(e && e.response && e.response.data){
              let data = e.response.data;
              if(data.validationErrors.length > 0){
                data.validationErrors.map(error => {
                  if(error.externalPropertyName === 'code unique')
                    message.error(messages('setting.key518'/*编码已存在，请重新输入*/))
                });
              }
            }
          })
        }
      }
    })
  };

  handleSelectIcon = (target) => {
    const { icon } = this.state;
    icon.iconURL = target.iconURL;
    icon.iconName = target.iconName;
    this.setState({ showIconSelectorFlag: false, icon });
  };

  handleChangeI18n = (value, i18n, type) => {
    this.setState({
      [type]: value,
      [`${type}I18n`]: i18n
    })
  };

  /**
   * 获取【可手工创建】按钮是否禁用
   * 禁用条件(或的关系)：
   * 1. 公司模式
   * 2. 补贴类型=“差旅补贴” subsidyType === 1
   * 3. 消费商费用类型 supplierType > 0 且 supplierType !== 15
   * 4. 里程补贴 supplierType === 15
   * 5. 扬招 messageKey === 'yangzhao'
   **/
  isManuallyCreatedDisabled = () => {
    const { tenantMode, expenseType } = this.props;
    const { subsidyType } = this.state;
    return (
      !tenantMode ||
      subsidyType === 1 ||
      (expenseType && expenseType.supplierType > 0) ||
      (expenseType && expenseType.messageKey === 'yangzhao')
    )
  };

  //修改补贴类型
  handleChangeSubsidyType = value => {
    const { setFieldsValue } = this.props.form;
    this.setState({ subsidyType: value });
    if (value === 1) {
      setFieldsValue({ isAbleToCreatedManually: false })
    }
  };

  render() {
    const { language } = this.props;
    const { getFieldDecorator, getFieldValue, setFieldsValue } = this.props.form;
    const {
      icon, showIconSelectorFlag, expenseTypeCategory, valid, saving, name, nameI18n, instructions, instructionsI18n,
      subsidyType
    } = this.state;
    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 8, offset: 1 },
    };
    const { expenseType, expenseTypeSetOfBooks, tenantMode, copy } = this.props;
    const expenseAttr = { // 费用属性值
      D: 'D', // 部门
      B: 'B', // 部门/餐厅
      S: 'S', // 餐厅
      N: 'N', // 餐厅包含临时餐厅
    }
    let options = [] // 费用属性选项
    for (let key in expenseAttr) {
      options.push(<Option value={key} key={key}>{expenseAttr[key]}</Option>)
    }
    return (
      <Form className="expense-type-base" onSubmit={this.handleSave}>
        <FormItem {...formItemLayout} label={messages('mcd.setting.expenseType.expenseAttr' /** 费用属性值 */)}>
          {getFieldDecorator('costAttribute', {
            rules: [{
              required: true,
              message: messages('common.please.select')
            }]
          })(
            <Select style={{ width: '100%' }} disabled={!tenantMode}>
              {options}
            </Select>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label={messages('common.column.status')}>
          {getFieldDecorator('enabled', {
            valuePropName: 'checked',
            initialValue: true
          })(
            <Switch onChange={checked => !checked && setFieldsValue({pushType: 'NOT_PUSH'})}/>
          )}
          <If value={expenseType && expenseType.readonly && expenseType.messageKey !== 'private.car.for.public' && !getFieldValue('enabled')}>
            <span className="status_disabled_tip">{messages('setting.key1753')/*禁用后将不再推送费用到账本*/}</span>
          </If>
        </FormItem>
        <FormItem {...formItemLayout} label={messages('setting.key519'/*选择图标*/)} required>
          <img src={icon.iconURL || defaultExpenseTypeIcon} className="expense-type-icon"
               onError={e => e.target.src = defaultExpenseTypeIcon}
               onClick={() => {tenantMode && this.setState({ showIconSelectorFlag: true })}}/>
        </FormItem>
        <FormItem {...formItemLayout} label={messages('setting.key520'/*费用类型名称*/)}>
          {getFieldDecorator('name', {
            rules: [{
              required: true,
              message: messages('common.please.enter')
            }]
          })(
            <LanguageInput
              name={name}
              i18nName={nameI18n}
              nameChange={(value, i18n) => this.handleChangeI18n(value, i18n, 'name')}
              isEdit={!!expenseType}
              inpRule={[{
                length: 30,
                language: "zh_cn"
              }, {
                length: 100,
                language: "en"
              }]}
              disabled={!tenantMode}
            />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label={
            <span>
              {messages('setting.key2218')/*费用类型提示*/}
              <Popover content={messages('setting.key2219')/*提示内容将在APP及PC端，选择费用类型时显示*/}>
                <Icon type="info-circle" className='default-color-font' style={{cursor: 'pointer', marginLeft: 5}} />
              </Popover>
            </span>
          }
        >
          {getFieldDecorator('instructions')(
            <LanguageInput
              name={instructions}
              i18nName={instructionsI18n}
              isEdit={!!expenseType}
              inpRule={[{
                length: 200,
                language: "zh_cn"
              }, {
                length: 600,
                language: "en"
              }]}
              textArea
              disabled={!tenantMode}
              placeholder={messages('common.max.characters.length', { max: language.code === 'zh_cn' ? 200 : 600 })}
              nameChange={(value, i18n) => this.handleChangeI18n(value, i18n, 'instructions')}
            />
          )}
        </FormItem>
        <FormItem {...formItemLayout} label={messages('setting.key521'/*编码*/)}>
          {getFieldDecorator('code', {
            rules: [{
              required: true,
              message: messages('common.please.enter')
            },{
              message: messages('setting.key522'/*不能输入空格*/),
              validator: (rule, value, cb) => {
                if (value === null || value === undefined || value === "") {
                  cb();
                  return;
                }
                if (!value.match(' ')) {
                  cb();
                } else {
                  cb(false);
                }
              }
            },{
              message: messages('setting.key523'/*不能输入汉字*/),
              validator: (rule, value, cb) => {
                if (value === null || value === undefined || value === "") {
                  cb();
                  return;
                }
                if (!/[\u4E00-\u9FA5]/i.test(value)) {
                  cb();
                } else {
                  cb(false);
                }
              }
            }]
          })(
            <Input maxLength="20" placeholder={messages('setting.key524'/*请输入，最多20个字符*/)} disabled={!!expenseType && !copy}/>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label={messages('setting.key246'/*账套*/)} required>
          <Input disabled value={expenseTypeSetOfBooks.setOfBooksName}/>
        </FormItem>
        <FormItem {...formItemLayout} label={messages('setting.key525'/*费用分类*/)}>
          {getFieldDecorator('expenseTypeCategoryId', {
            rules: [{
              required: true,
              message: messages('common.please.select')
            }]
          })(
            <Select style={{ width: '100%' }} disabled={!tenantMode}>
              {expenseTypeCategory.map(item => <Option value={item.id} key={item.id}>{item.name}</Option>)}
            </Select>
          )}
        </FormItem>
        {<FormItem {...formItemLayout} label={messages('setting.key526'/*类型*/)}>
          {getFieldDecorator('depth', {
            rules: [{
              required: true,
              message: messages('common.please.select'),
            }],
            initialValue: (expenseType && expenseType.depth) ? expenseType.depth : 2
          })(
            <Select style={{width: '100%'}} disabled={!!expenseType && !copy}>
              <Option value={1}>{messages('setting.key527'/*父类型*/)}</Option>
              <Option value={2}>{messages('setting.key528'/*子类型*/)}</Option>
            </Select>
          )}
        </FormItem>}
        {Number(getFieldValue('depth')) === 2 && <FormItem {...formItemLayout} label={messages('setting.key529'/*所属父类型*/)}>
          {getFieldDecorator('parentId', {
            rules: [{
              required: false,
              message: messages('common.please.select'),
            }],
            initialValue: (expenseType && expenseType.parentId && expenseType.parentId !== '-1') ? [{
              name: expenseType.parentName || '',
              id: expenseType.parentId
            }] : undefined
          })(
            <Chooser listExtraParams={{setOfBooksId: expenseTypeSetOfBooks.id, depth: 1, enabled: true}}
                     valueKey="id"
                     type='select_relate_invoiceType'
                     disabled={(expenseType && expenseType.parentId && !copy) || !tenantMode}
                     labelKey="name"
                     single/>
          )}
        </FormItem>}
        <FormItem {...formItemLayout} label={messages('setting.key530'/*补贴类型*/)}>
          {getFieldDecorator('subsidyType', {
            initialValue: 0
          })(
            <Select style={{ width: '100%' }} disabled={!!expenseType && !copy} onChange={this.handleChangeSubsidyType}>
              <Option value={0}>{messages('setting.key506'/*非补贴*/)}</Option>
              <Option value={1}>{messages('setting.key507'/*差旅补贴*/)}</Option>
              {/*<Option value={2}>{messages('expense.type.daily.allowance')}</Option>*/}
            </Select>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label={messages('setting.key2086')/*生成费用的对账状态*/}>
          {getFieldDecorator('confirmationStatus', {
            initialValue: 'all'
          })(
            <Select
              disabled={!tenantMode}
              style={{ width: '100%' }}
              getPopupContainer={() => document.getElementsByClassName('new-expense-type')[0]}
              onChange={value => this.setState({ confirmationStatus: value })}>
              <Option value={'all'}>{messages('common.all')/*全部*/}</Option>
              <Option value={'confirmed'}>{messages('setting.key2087')/*已确认*/}</Option>
              <Option value={'unconfirmed'}>{messages('setting.key2088')/*未确认*/}</Option>
            </Select>
          )}
            <span className="status_disabled_tip">{messages('setting.key2089')/*说明：只针对公司支付费用*/}</span>
        </FormItem>
        {expenseType && expenseType.supplierType > 0 && expenseType.supplierType !== 15 /*里程补贴不显示*/ && (
          <FormItem {...formItemLayout} label={messages('setting.key531'/*推送设置*/)}>
            {getFieldDecorator('pushType', {
              initialValue: expenseType.pushType
            })(
              <Select
                style={{ width: '100%' }}
                getPopupContainer={() => document.getElementsByClassName('new-expense-type')[0]}
                disabled={!tenantMode || !getFieldValue('enabled')}>
                <Option value="NOT_PUSH">{messages('setting.key2090')/*不推送到员工账本*/}</Option>
                <Option value="PERSONAL_PAY">{messages('setting.key2091')/*推送个人支付费用到员工账本*/}</Option>
                <Option value="COMPANY_PAY">{messages('setting.key2092')/*推送公司支付费用到员工账本*/}</Option>
                <Option value="ALL">{messages('setting.key2093')/*推送个人、公司支付费用到员工账本*/}</Option>
              </Select>
            )}
          </FormItem>
        )}
        <If value={(expenseType || {}).showServiceFeeSplit}>
          <FormItem{...formItemLayout} label={(
            <span>
              {messages('setting.key1754')/*费用推送形式*/}
              <Popover
                content={messages('setting.key2220')/*此管控不适用于携程机票单独推送“后收服务费”，单独推送数据默认为“携程机票服务费”类型*/}
                overlayStyle={{maxWidth: 400}}
              >
                <Icon type="info-circle" className='default-color-font' style={{cursor: 'pointer', marginLeft: 5}} />
              </Popover>
            </span>
          )}>
            {getFieldDecorator('serviceFeeSplit', {
              initialValue: Number((expenseType || {}).serviceFeeSplit || 0)
            })(
              <Select style={{ width: '100%' }} disabled={!tenantMode} getPopupContainer={() => document.getElementsByClassName('new-expense-type')[0]}>
                <Option value={0}>{messages('setting.key1755')/*票面费用和服务费推一笔费用*/}</Option>
                <Option value={1}>{messages('setting.key1756')/*票面费用和服务费推两笔费用*/}</Option>
                <Option value={2}>{messages('setting.key1757')/*只推票面费用（不推送服务费）*/}</Option>
              </Select>
            )}
          </FormItem>
        </If>
        {(!expenseType || expenseType.supplierType === 0 ||  expenseType.supplierType === 15 /*里程补贴显示*/) && (
          <FormItem {...formItemLayout} label={messages('setting.key536'/*是否有票*/)}>
            {getFieldDecorator('pasteInvoiceNeeded', {
              initialValue: expenseType ? Number(expenseType.pasteInvoiceNeeded) : 1
            })(
              <Select optionLabelProp="title" style={{ width: '100%' }} disabled={!tenantMode}>
                <Option value={1} title={messages('setting.key537'/*有票*/)}>
                  {messages('setting.key537'/*有票*/)}<br/>
                  <span style={{ color: '#ccc' }}>{messages('setting.key538'/*员工报销时需贴票*/)}</span>
                </Option>
                <Option value={0} title=
                  {messages('setting.key539'/*无票*/)}>
                  {messages('setting.key539'/*无票*/)}<br/>
                  <span style={{ color: '#ccc' }}>{messages('setting.key540'/*员工报销时无需贴票*/)}</span>
                </Option>
              </Select>
            )}
          </FormItem>
        )}
        <FormItem {...formItemLayout} label={messages('setting.key2221')/*可手工创建*/}>
          {getFieldDecorator('isAbleToCreatedManually', {
            valuePropName: 'checked',
            initialValue: expenseType ? expenseType.isAbleToCreatedManually : true
          })(
            <Switch disabled={this.isManuallyCreatedDisabled()}/>
          )}
        </FormItem>
        <hr style={{borderColor: '#fff', marginBottom: 24}}/>
        <FormItem {...formItemLayout} label={messages('setting.key541'/*金额录入模式*/)}>
          <Row gutter={20}>
            <Col span={18}>
              {getFieldDecorator('valid', {
                initialValue: 0
              })(
                <Select style={{ width: '100%' }}
                        onChange={value => this.setState({ valid: value })}
                        disabled={!tenantMode || (expenseType && expenseType.supplierType > 0)}>
                  <Option value={0}>{messages('setting.key542'/*总金额*/)}</Option>
                  <Option value={1}>{messages('setting.key543'/*单价*数量*/)}</Option>
                </Select>
              )}
            </Col>
            {valid === 1 && (
              <Col span={6}>
                {getFieldDecorator('unit', {
                  initialValue: (expenseType && expenseType.unit) ? expenseType.unit :  "day"
                })(
                  <Select style={{ width: '100%' }} disabled={!tenantMode}>
                    <Option value="day">{messages('setting.key544'/*天*/)}</Option>
                    <Option value="weak">{messages('setting.key545'/*周*/)}</Option>
                    <Option value="month">{messages('setting.key546'/*月*/)}</Option>
                    <Option value="person">{messages('setting.key547'/*人*/)}</Option>
                    <Option value="unit">{messages('setting.key548'/*个*/)}</Option>
                    <Option value="th">{messages('setting.key549'/*次*/)}</Option>
                  </Select>
                )}
              </Col>
            )}
          </Row>
        </FormItem>
        {expenseType && expenseType.supplierType > 0 && (expenseType.supplierType !== 15 /*里程补贴不显示*/) && (
          <FormItem {...formItemLayout} label={messages('setting.key550'/*是否可修改金额*/)}>
            {getFieldDecorator('isAmountEditable', {
              valuePropName: 'checked',
              initialValue: expenseType ? expenseType.isAmountEditable : true
            })(
              <Switch disabled={!tenantMode}/>
            )}
          </FormItem>
        )}
        <FormItem {...formItemLayout} label={messages('setting.key551'/*是否分摊*/)}>
          {getFieldDecorator('apportionEnabledConfig', {
            initialValue: []
          })(
            <Checkbox.Group style={{ width: '100%' }} disabled={!tenantMode}>
              <Row>
                <Col span={8}>
                  <Checkbox value="erApportionEnabled">{messages('setting.key847')/*报销单*/}</Checkbox>
                </Col>
                <Col span={8}>
                  <Checkbox value="apportionEnabled">{messages('setting.key20')/*申请单*/}</Checkbox>
                </Col>
              </Row>
            </Checkbox.Group>
          )}
        </FormItem>
        {getFieldValue('apportionEnabledConfig')[0] && (
          <FormItem {...formItemLayout} label={messages('setting.key552'/*分摊范围*/)}>
            {getFieldDecorator('apportionmentDataScope', {
              initialValue: expenseType ? expenseType.apportionmentDataScope : 0
            })(
              <Select style={{ width: '100%' }} disabled={!tenantMode}>
                <Option value={0}>{messages('setting.key553'/*帐套下启用中的成本项*/)}</Option>
                <Option value={1}>{messages('setting.key554'/*员工权限下启用中的成本项*/)}</Option>
              </Select>
            )}
          </FormItem>
        )}
        <FormItem {...formItemLayout} label={messages('common.attachments')}>
          {getFieldDecorator('attachmentRequired', {
            initialValue: 0
          })(
            <Select optionLabelProp="title" style={{ width: '100%' }} disabled={!tenantMode}>
              <Option value={1} title={messages('setting.key555'/*始终必填*/)}>{messages('setting.key555'/*始终必填*/)}</Option>
              <Option value={0} title={messages('setting.key556'/*始终不必填*/)}>{messages('setting.key556'/*始终不必填*/)}</Option>
              <Option value={3} title={messages('setting.key557'/*仅有发票原件时不必填*/)}>{messages('setting.key557'/*仅有发票原件时不必填*/)}<br/><span style={{ color: '#ccc' }}>{messages('setting.key558'/*费用关联了发票电子原件时，附件不必填*/)}</span></Option>
              <Option value={2} title={messages('setting.key559'/*有发票时始终不必填*/)}>{messages('setting.key559'/*有发票时始终不必填*/)}<br/><span
                style={{ color: '#ccc', whiteSpace: 'normal'}}>
                {messages('setting.key560'/*费用中有导入、扫入、录入发票时或费用为无票时，附件不必填，其余情况必填*/)}</span></Option>
            </Select>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label={messages('setting.key1535')/*是否支持多发票*/}>
          {getFieldDecorator('multipleInvoiceSupported', {
            valuePropName: 'checked',
            initialValue: false
          })(
            <Switch disabled={!tenantMode}/>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label={messages('setting.key1802')/*发票控件是否必填*/}>
          {getFieldDecorator('invoiceRequired', {
            valuePropName: 'checked',
            initialValue: false
          })(
            <Switch disabled={!tenantMode}/>
          )}
        </FormItem>
        <FormItem {...formItemLayout} label={messages('setting.key1880')/*参与行程计算*/}>
          {getFieldDecorator('tripStatisticsEnabled', {
            valuePropName: 'checked',
            initialValue: false
          })(
            <Switch disabled={!tenantMode}/>
          )}
        </FormItem>
        <FormItem {...formItemLayout} wrapperCol={{ offset: 5 }} className="form-buttons">
          <Button type="primary" htmlType="submit" loading={saving}>{messages('common.save')}</Button>
          <Button style={{ marginLeft: 8 }} onClick={this.goBack}>{messages('common.back')}</Button>
        </FormItem>
        <IconSelector visible={showIconSelectorFlag}
                      onOk={this.handleSelectIcon}
                      onCancel={() => this.setState({ showIconSelectorFlag: false })}/>
      </Form>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    language: state.main.language,
    expenseTypeSetOfBooks: state.setting.expenseTypeSetOfBooks,
    tenantMode: state.main.tenantMode
  }
}

ExpenseTypeBase.propTypes = {
  expenseType: React.PropTypes.object,
  onSave: React.PropTypes.func,
  copy: React.PropTypes.bool // 判断是否是复制类型的费用
};

ExpenseTypeBase.contextTypes = {
  router: React.PropTypes.object
};


const WrappedExpenseTypeBase = Form.create()(ExpenseTypeBase);

export default connect(mapStateToProps)(WrappedExpenseTypeBase)
